<template>
    <div class="protected-container">
        <a-card title="受保护的页面" :style="{ width: '600px' }">
            <template #extra>
                <a-button type="primary" @click="logout">退出登录</a-button>
            </template>
            <div class="user-info">
                <h3>当前用户信息：</h3>
                <p>用户名：{{ userInfo.username }}</p>
                <p>角色：{{ userInfo.roles?.join(', ') }}</p>
                <p>Token：{{ token }}</p>
            </div>
            <div class="login-source">
                <p>登录来源：{{ loginSource }}</p>
            </div>
        </a-card>
    </div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

export default defineComponent({
    name: 'Protected',
    setup() {
        const store = useStore();
        const router = useRouter();

        const userInfo = computed(() => store.state.userInfo);
        const token = computed(() => store.state.token);
        const loginSource = computed(() => 
            qiankunWindow.__POWERED_BY_QIANKUN__ ? '主应用' : '子应用'
        );

        const logout = () => {
            // 清除本地状态
            store.commit('setToken', '');
            store.commit('setUserInfo', {});
            store.commit('setIsLogin', false);

            // 如果在qiankun环境中，同步状态到主应用
            if (qiankunWindow.__POWERED_BY_QIANKUN__) {
                // @ts-ignore
                const { setGlobalState } = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
                setGlobalState({
                    token: '',
                    userInfo: {},
                    isLogin: false
                });
            }

            message.success('已退出登录');
            router.push('/login');
        };

        return {
            userInfo,
            token,
            loginSource,
            logout
        };
    }
});
</script>

<style lang="less" scoped>
.protected-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;

    .user-info {
        margin-bottom: 20px;
        p {
            margin: 8px 0;
        }
    }

    .login-source {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #e8e8e8;
    }
}
</style> 